package com.acme.chat.server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class TCPServer implements Runnable {
    private volatile boolean keepGoing;

    private int port;
    private ServerSocket serverSocket;
    private Server server;

    public TCPServer(Server server, int port) {
        this.server = server;
        this.port = port;
        init();
    }

    private void init() {
        try {
            this.serverSocket = new ServerSocket(port);
        } catch (IOException e) {
            System.out.println("Can't create ServerSocket on port " + port);
            e.printStackTrace();
        }
    }

    public void run() {
        keepGoing = true;
        while (keepGoing) {
            Socket socket = null;
            try {
                socket = serverSocket.accept();
            } catch (IOException e) {
                e.printStackTrace();
            }

            if (!keepGoing) {
                break;
            }
            TcpProxyClient tcpProxyClient = new TcpProxyClient(socket, server);
            tcpProxyClient.start();
            // TCPClient client = new TCPClient(socket, server);
            // client.start();
        }

        try {
            serverSocket.close();
        } catch (Exception e) {
            System.out.println("Error closing the server: " + e);
            e.printStackTrace();
        }
    }

    public void stop() {
        keepGoing = false;
        try {
            new Socket("localhost", port);
        } catch (Exception e) {
        }
    }

    public static void main(String[] args) {
        int portNumber = 1800;
        switch (args.length) {
        case 1:
            try {
                portNumber = Integer.parseInt(args[0]);
            } catch (Exception e) {
                System.out.println("Invalid port number.");
                System.out.println("Usage is: > java Server [portNumber]");
                return;
            }
        case 0:
            break;
        default:
            System.out.println("Usage is: > java Server [portNumber]");
            return;

        }
        Server server = new ServerImpl();
        TCPServer tcpServer = new TCPServer(server, portNumber);
        Thread thread = new Thread(tcpServer);
        thread.start();

//        new ClientGUI("localhost", 1800);
    }

}
